#!/data/data/com.termux/files/usr/bin/bash

# 路径和文件
PKG_BIN=$PREFIX/bin
GPG_FILE=$PREFIX/etc/apt/trusted.gpg.d/tur.gpg
SLF=$PREFIX/etc/termux/chosen_mirrors
CMF=$PREFIX/etc/termux/mirrors/chinese_mainland/mirrors.ustc.edu.cn

# 函数，判断文件不存在后安装
IPIF_IP(){
  if [ ! -f $1 ];then
    echo -e "\e[34m [#] 安装 $2 ...\e[0m"
    if ! pkg install -y $2;then
      echo -e "\e[31m [!] 错误: $2 安装失败\e[0m"
      exit 1
    fi
  else
    echo -e "\e[32m [*] $2: 已安装\e[0m"
  fi
}

# 函数，判断命令存在
IPIF(){
  if [ -x $(command -v $1) ];then
    echo -e "\e[34m [#] 正在执行 $1...\e[0m"
    $@
  else
    echo -e "\e[31m [!] 错误: $1: 找不到命令\e[0m"
    exit
  fi
}

# 更新源
yes | pkg up -y
[ -L $SLF ] &&
unlink $SLF
ln -s $CMP $SLF
pkg --check-mirror update
pkg i git -y

# 安装所需软件/源
IPIF_IP $GPG_FILE tur-repo
IPIF_IP $PKG_BIN/git git
IPIF_IP $PKG_BIN/node nodejs-lts
IPIF_IP $PKG_BIN/redis-server redis
IPIF_IP $PKG_BIN/chromium-browser chromium
IPIF_IP $PKG_BIN/ar binutils

# 使用 corepack 安装 pnpm
if ! [ -x $(command -v pnpm) ];then
  IPIF corepack enable pnpm
  if ! yes | pnpm -v 2>/dev/null;then
    echo -e "\e[31m [!] 错误: pnpm 安装失败\e[0m"
    exit 1
  fi
else
  echo -e "\e[32m [*] pnpm: 已安装\e[0m"
fi

# 此处使用 pnpm 临时添加环境变量
if ! [[ $PATH == *pnpm* ]];then
  pnpm setup
  source ~/.bashrc
fi

# 全局安装 cnpm
if ! [ -x $(command -v cnpm) ];then
  if ! pnpm install cnpm -g;then
    echo -e "\e[31m [!] 错误: cnpm 安装失败\e[0m"
    exit 1
  fi
else
  echo -e "\e[32m [*] cnpm: 已安装\e[0m"
fi